<template>
  <je-modal
    v-model:visible="visible"
    class="childfuncfield-adds-configinfo"
    width="1200px"
    :title="title"
    :resize="false"
    :maximizable="false"
    cancel-button
    :ok-button="handleOk"
    @close="handleClose"
  >
    <je-form
      ref="formRef"
      class="childfuncfield-adds-configinfo-form"
      :rules="rules"
      :model="formState"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      size="small"
      autocomplete="off"
    >
      <je-collapse v-model:activeKey="activeKey" expand-icon-position="right">
        <je-collapse-panel key="1" header="核心配置">
          <je-row>
            <je-col :span="8">
              <je-form-item label="目标功能" name="funcName">
                <je-grid-select
                  v-model:value="formState.funcName"
                  name="funcName"
                  config-info="JE_CORE_FUNCINFO,funcName~funcCode~funcId,FUNCINFO_FUNCNAME~FUNCINFO_FUNCCODE~JE_CORE_FUNCINFO_ID,S"
                  :querys="[
                    {
                      code: 'FUNCINFO_FUNCTYPE',
                      type: 'in',
                      value: ['TREE', 'FUNC', 'VIEW'],
                      cn: 'and',
                    },
                  ]"
                  @select="selectfuncNameRow"
                /> </je-form-item
            ></je-col>
            <je-col :span="8">
              <je-form-item label="功能编码" name="funcCode">
                <je-input v-model:value="formState.funcCode" disabled />
              </je-form-item>
            </je-col>
            <je-col :span="8">
              <je-form-item label="使用方案" name="schemeType">
                <je-select v-model:value="formState.schemeType" allow-clear disabled>
                  <je-select-option
                    v-for="(item, index) in [
                      {
                        code: 'grid',
                        text: '默认列表方案',
                      },
                    ]"
                    :key="index"
                    :value="item.code"
                  >
                    {{ item.text }}
                  </je-select-option>
                </je-select>
              </je-form-item></je-col
            >
          </je-row>
          <je-row>
            <je-col :span="16">
              <je-form-item label="条件说明" name="querysExplain">
                <je-input v-model:value="formState.querysExplain"> </je-input>
              </je-form-item>
            </je-col>
            <je-col :span="8">
              <je-form-item label="选择方式" name="selModel">
                <je-select v-model:value="formState.selModel" allow-clear disabled>
                  <je-select-option
                    v-for="(item, index) in [
                      { code: 'S', text: '单选' },
                      { code: 'M', text: '多选' },
                    ]"
                    :key="index"
                    :value="item.code"
                  >
                    {{ item.text }}
                  </je-select-option>
                </je-select>
              </je-form-item>
            </je-col>
            <je-col :span="16">
              <je-form-item name="querys">
                <template #label>
                  <div class="iconWrap" @click.stop="showSqlWin">
                    <i class="fal fa-filter" style="color: #8d98ab"></i>
                    过滤条件
                  </div>
                </template>
                <je-input v-model:value="formState.querys" />
              </je-form-item>
            </je-col>
          </je-row>
        </je-collapse-panel>
        <je-collapse-panel key="3" header="带值规则">
          <div class="tableWrap">
            <je-table
              class="table"
              border
              show-overflow="ellipsis"
              keep-source
              sync-resize
              auto-resize
              draggable
              :style="`height: ${tableHeight} `"
              :scroll-y="{ mode: 'wheel' }"
              :edit-config="{
                trigger: 'click',
                mode: 'cell',
                showUpdateStatus: true,
              }"
              :store="codes"
              size="mini"
              header-align="center"
              @drop="codesArrDrop"
            >
              <!--@current-change="getSelectData" -->
              <je-table-column field="index" title="序号" width="50" align="center">
              </je-table-column>
              <je-table-column field="pkName" title="唯一" width="50" align="center" type="switch">
                <!-- <template #default="{ row }"> -->
                <!-- <je-switch v-model:value="row.pkName" mode="checkbox" /> -->
                <!-- </template> -->
              </je-table-column>
              <je-table-column field="name" title="目标功能字段">
                <template #edit="{ row }">
                  <je-input v-model:value="row.name" disabled />
                </template>
              </je-table-column>
              <je-table-column field="code" title="字段编码" width="220">
                <template #edit="{ row }">
                  <je-input v-model:value="row.code" disabled />
                </template>
              </je-table-column>
              <je-table-column width="40" align="center">
                <template #header>
                  <i
                    style="font-size: 16px; cursor: pointer"
                    class="fal fa-plus"
                    @click="addColumn"
                  ></i>
                </template>
                <template #default="{ row }">
                  <i
                    style="font-size: 16px; cursor: pointer"
                    class="fal fa-times"
                    @click="deleteColumn('codes', row)"
                  ></i>
                </template>
              </je-table-column>
            </je-table>
            <div style="cursor: pointer"
              ><je-tooltip
                title="基于左侧数据匹配右侧数据"
                @click="intelligentTransition(formState.funcId, 'left')"
              >
                <i
                  class="fal fa-angle-double-right icon-class"
                  style="margin-bottom: 20px"
                ></i> </je-tooltip
              ><br />
              <je-tooltip
                title="基于右侧数据匹配左侧数据"
                @click="intelligentTransition(formState.funcId, 'right')"
              >
                <i class="fal fa-angle-double-left icon-class"></i>
              </je-tooltip>
            </div>
            <je-table
              class="table"
              border
              show-overflow="ellipsis"
              keep-source
              :style="`height: ${tableHeight} `"
              :scroll-y="{ mode: 'wheel' }"
              draggable=""
              :edit-config="{
                trigger: 'click',
                mode: 'cell',
                showUpdateStatus: true,
              }"
              :store="selfCodes"
              size="mini"
              header-align="center"
              @drop="selfCodesArrDrop"
            >
              <je-table-column field="index" title="序号" width="50" align="center">
              </je-table-column>
              <je-table-column field="name" title="本功能字段">
                <template #edit="{ row }">
                  <je-input v-model:value="row.name" disabled />
                </template>
              </je-table-column>
              <je-table-column field="code" title="字段编码" width="220">
                <template #edit="{ row }">
                  <je-input v-model:value="row.code" disabled />
                </template>
              </je-table-column>
              <je-table-column width="40" align="center">
                <template #header>
                  <i
                    style="font-size: 16px; cursor: pointer"
                    class="fal fa-plus"
                    @click="addColumnSelf"
                  ></i>
                </template>
                <template #default="{ row }">
                  <i
                    style="font-size: 16px; cursor: pointer"
                    class="fal fa-times"
                    @click="deleteColumn('selfCodes', row)"
                  ></i>
                </template>
              </je-table-column>
            </je-table>
          </div>
          <template #extra
            ><i
              :class="[activeKey.length > 1 ? 'jeicon jeicon-an' : 'jeicon jeicon-packup']"
              style="padding-right: 30px; cursor: pointer"
              @click="handleClick"
            ></i
          ></template>
        </je-collapse-panel>
      </je-collapse>
    </je-form>
  </je-modal>
</template>

<script>
  import { ref, toRefs, reactive, defineComponent, onMounted, nextTick } from 'vue';
  import { Collapse, Row, Col } from 'ant-design-vue';
  import { showFuncQuerys } from '@jecloud/func';

  import { SelectWindow } from '@jecloud/func';

  import { Grid, Modal, Form, Input, Select, InputSelect, Data } from '@jecloud/ui';

  import { getData, SearchintelligentTransition } from '@/api/index';
  import { encode, isNotEmpty } from '@jecloud/utils';
  export default defineComponent({
    name: 'ChildfuncfieldAddsConfiginfo',
    components: {
      JeModal: Modal,
      JeCollapse: Collapse,
      JeCollapsePanel: Collapse.Panel,
      JeRow: Row,
      JeCol: Col,
      JeForm: Form,
      JeFormItem: Form.Item,
      JeInput: Input,
      JeSelect: Select,
      JeSelectOption: Select.Option,
      JeGridSelect: InputSelect.Grid,
      JeTable: Grid,
      JeTableColumn: Grid.Column,
    },
    props: {
      visble: {
        type: Boolean,
        default: false,
      },
      recordData: {
        type: Object,
        default: () => {},
      },
      funcData: Object,
      addsconfig: String,
    },
    emits: ['changeModal'],
    setup(props, { emit }) {
      const state = reactive({
        tableHeight: `calc(100vh - 485px)`,
        visible: props.visble,
        title: '批量添加配置',
        activeKey: ['1', '3'],
        formRef: ref(),
        formState: {
          funcId: props.recordData?.funcId || '',
          funcCode: props.recordData?.funcCode || '',
          funcName: props.recordData?.funcName || '',
          schemeType: props.recordData?.schemeType || 'grid',
          querysExplain: props.recordData?.querysExplain || '',
          selModel: props.recordData?.selModel || 'M',
          querys: props.recordData?.querys || '',
        },
        labelCol: {
          style: { width: '100px' },
        },
        wrapperCol: {},
        rules: {},
        selfCodes: Data.Store.useGridStore({
          data: [],
        }),
        codes: Data.Store.useGridStore({
          data: [],
        }),
        funcId: '',
      });
      onMounted(() => {
        nextTick(() => {
          methods.getFuncId(props.funcData.RESOURCEFIELD_CONFIGINFO);
          if (props.recordData?.selfCodes.length > 0) {
            state.selfCodes.loadData(props.recordData.selfCodes);
          } else {
            if (isNotEmpty(props.addsconfig)) {
              const conf1 = props.addsconfig.split(',')[1];
              const conf0 = props.addsconfig.split(',')[0];
              if (isNotEmpty(conf0)) {
                state.formState.funcCode = conf0;
                state.formState.funcName = conf0;
              }
              if (isNotEmpty(conf1)) {
                const selfTableData = [];
                conf1.split('~').forEach((item, _index) => {
                  selfTableData.push({ index: _index + 1, name: item, code: item });
                });
                state.selfCodes.loadData(selfTableData);
              }
            }
          }
          if (props.recordData?.codes.length > 0) {
            state.codes.loadData(props.recordData.codes);
          } else {
            if (isNotEmpty(props.addsconfig)) {
              const conf2 = props.addsconfig.split(',')[2];
              if (isNotEmpty(conf2)) {
                const codeTableData = [];
                conf2.split('~').forEach((item, _index) => {
                  codeTableData.push({ index: _index + 1, name: item, code: item, pkName: 0 });
                });
                state.codes.loadData(codeTableData);
              }
            }
          }
        });
      });
      const methods = {
        // 智能切换
        intelligentTransition(id, type) {
          const codeArr = [];
          // 获取当前功能字段的字符串state.selfCodes.data
          if (type == 'left') {
            state.codes.data.forEach((item) => {
              const ele = `${item.code}~${item.name}`;
              codeArr.push(ele);
            });
          }
          if (type == 'right') {
            state.selfCodes.data.forEach((item) => {
              const ele = `${item.code}~${item.name}`;
              codeArr.push(ele);
            });
          }

          const params = {
            targetFuncId: id,
            consultFields: codeArr.join(','),
          };
          if (!params.consultFields && type == 'left') {
            Modal.alert('请先添加目标功能字段！', 'info');
            return false;
          }
          if (!params.consultFields && type == 'right') {
            Modal.alert('请先添加本功能字段！', 'info');
            return false;
          }
          SearchintelligentTransition(params)
            .then((res) => {
              if (type == 'left') {
                const codeRes = res.data.current || [];
                const selfRes = res.data.target || [];
                let newCodes = [];
                const newSelf = [];
                const newCodesConcat = [];
                codeRes.map((item) => {
                  const arrItem = item.split('~');
                  // [0]是code
                  const newItemArr = state.codes.data.filter((_item) => arrItem[0] == _item.code);
                  newItemArr.map((_item, index) => {
                    if (index < 1) {
                      newCodes.push(_item);
                    } else {
                      newCodesConcat.push(_item);
                    }
                  });
                });
                newCodes = newCodes.concat(newCodesConcat);
                newCodes.map((item, index) => {
                  item.index = index + 1;
                  return item;
                });
                state.codes.loadData(newCodes);
                selfRes.forEach((item, index) => {
                  const arrItem = item.split('~');
                  // [0]是code
                  const newItem = {
                    code: arrItem[0],
                    name: arrItem[1],
                    pkName: '0',
                    index: index + 1,
                  };
                  newSelf.push(newItem);
                });
                state.selfCodes.loadData(newSelf);
              } else {
                const codeRes = res.data.current || [];
                const selfRes = res.data.target || [];
                let newCodes = [];
                const newSelf = [];
                const newCodesConcat = [];
                codeRes.map((item) => {
                  const arrItem = item.split('~');
                  // [0]是code
                  const newItemArr = state.selfCodes.data.filter(
                    (_item) => arrItem[0] == _item.code,
                  );
                  newItemArr.map((_item, index) => {
                    if (index < 1) {
                      newCodes.push(_item);
                    } else {
                      newCodesConcat.push(_item);
                    }
                  });
                });
                newCodes = newCodes.concat(newCodesConcat);
                newCodes.map((item, index) => {
                  item.index = index + 1;
                  return item;
                });
                state.selfCodes.loadData(newCodes);
                selfRes.forEach((item, index) => {
                  const arrItem = item.split('~');
                  // [0]是code
                  const newItem = {
                    code: arrItem[0],
                    name: arrItem[1],
                    pkName: '0',
                    index: index + 1,
                  };
                  newSelf.push(newItem);
                });
                state.codes.loadData(newSelf);
              }
            })
            .catch((err) => {
              Modal.alert(err.message, 'error');
            });
        },
        getFuncId(config) {
          if (config) {
            const funcCode = config.split(',')[0];
            if (funcCode) {
              getData({
                tableCode: 'JE_CORE_FUNCINFO',
                j_query: encode([{ code: 'FUNCINFO_FUNCCODE', type: '=', value: funcCode }]),
              }).then((data) => {
                if (data.length > 0) {
                  state.funcId = data[0].JE_CORE_FUNCINFO_ID;
                }
              });
            }
          }
        },

        handleClose() {
          state.visible = false;
          emit('changeModal', { type: 'close' });
        },

        // 选择目标功能，获取功能Id,code
        selectfuncNameRow({ rows }) {
          if (rows && rows.length) {
            state.formState.funcId = rows[0].JE_CORE_FUNCINFO_ID;
            state.formState.funcCode = rows[0].FUNCINFO_FUNCCODE;
          }
        },

        showSqlWin() {
          showFuncQuerys({
            funcId: state.formState.funcId || '',
            value: state.formState.querys || '',
            callback: (val) => {
              state.formState.querys = val;
            },
          });
        },

        // 拖拽排序目标功能字段
        codesArrDrop() {
          state.codes.data.forEach((item, index_) => {
            item.index = index_ + 1;
          });
        },
        // 本功能字段
        selfCodesArrDrop() {
          state.selfCodes.data.forEach((item, index_) => {
            item.index = index_ + 1;
          });
        },
        handleClick(event) {
          if (state.activeKey.length == 1) {
            state.activeKey = ['1', '2', '3'];
            state.tableHeight = `calc(100vh - 485px)`;
          } else {
            state.tableHeight = `calc(100vh - 340px)`;
            state.activeKey = ['3'];
          }
          event.stopPropagation();
        },
        //删除列
        deleteColumn(key, row) {
          state[key].remove(row);
        },

        // 目标功能添加字段
        addColumn() {
          if (!state.formState.funcName) {
            Modal.alert('请先选择目标功能在进行字段添加！', 'info');
            return false;
          }
          //列表现有的code值
          const columnCode = [];
          state.codes.data.forEach((item) => {
            columnCode.push(item.code);
          });

          // 目标功能中字段的选择
          SelectWindow.show({
            title: '目标功能字段',
            type: 'grid',
            orders: [
              // { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ],
            querys: [
              {
                code: 'RESOURCECOLUMN_FUNCINFO_ID',
                value: state.formState.funcId,
                type: '=',
                cn: 'and',
              },
              // {
              //   code: 'RESOURCECOLUMN_CODE',
              //   value: columnCode,
              //   type: 'notIn',
              //   cn: 'and',
              // },
              {
                code: 'RESOURCECOLUMN_XTYPE',
                value: 'uxcolumn',
                type: '=',
                cn: 'and',
              },
              // { code: 'TABLECOLUMN_ISCREATE', type: '=', value: '1', cn: 'and' },
            ],
            configInfo: 'JE_CORE_RESOURCECOLUMN,,,M',
            callback: function ({ rows }) {
              //  对选择数据进行处理，变成code , text
              if (rows && rows.length) {
                const data = [];
                rows.forEach((item, index) => {
                  const { RESOURCECOLUMN_CODE, RESOURCECOLUMN_NAME } = item;
                  data.push({
                    code: RESOURCECOLUMN_CODE,
                    name: RESOURCECOLUMN_NAME,
                    pkName: '0',
                    index: state.codes.data.length + index + 1,
                  });
                });
                state.codes.insert(data, -1);
              }
            },
          });
        },
        // 本功能添加字段
        addColumnSelf() {
          // 本功能ID： state.formState.RESOURCEFIELD_FUNCINFO_ID

          //列表现有的code值
          const columnCode = [];
          state.selfCodes.data.forEach((item) => {
            columnCode.push(item.code);
          });

          SelectWindow.show({
            title: '本功能字段',
            type: 'grid',
            orders: [
              // { code: 'TABLECOLUMN_CLASSIFY', type: 'ASC' },
              { code: 'SY_ORDERINDEX', type: 'ASC' },
            ],
            querys: [
              {
                code: 'RESOURCECOLUMN_FUNCINFO_ID',
                value: state.funcId,
                type: '=',
                cn: 'and',
              },
              {
                code: 'RESOURCECOLUMN_CODE',
                value: columnCode,
                type: 'notIn',
                cn: 'and',
              },
              {
                code: 'RESOURCECOLUMN_XTYPE',
                value: 'uxcolumn',
                type: '=',
                cn: 'and',
              },
            ],
            configInfo: 'JE_CORE_RESOURCECOLUMN,,,M',
            callback: function ({ rows }) {
              //  对选择数据进行处理，变成code , text
              if (rows && rows.length) {
                const data = [];
                rows.forEach((item, index) => {
                  const { RESOURCECOLUMN_CODE, RESOURCECOLUMN_NAME } = item;
                  data.push({
                    code: RESOURCECOLUMN_CODE,
                    name: RESOURCECOLUMN_NAME,
                    pkName: '0',
                    index: state.selfCodes.data.length + index + 1,
                  });
                });
                state.selfCodes.insert(data, -1);
              }
            },
          });
        },
        handleOk() {
          if (state.codes.data.length !== state.selfCodes.data.length) {
            Modal.alert('两组字段对应的条数不相同，请重新选择！', 'warning');
            return false;
          }
          let { funcCode, selModel } = state.formState;
          let addsConfigInfo = {};
          const addCfgs = { addsConfigInfo: '', addsOtherConfig: {} };
          let pkNames = [],
            codesIndex = '';
          addsConfigInfo = [funcCode, [], [], selModel];
          // 封装目标功能列表数据
          state.codes.data.forEach((item, index) => {
            if (item.pkName == '1') {
              pkNames.push(item.code);
              codesIndex = index;
            }
            addsConfigInfo[2].push(item.code);
          });
          if (pkNames.length > 1) {
            Modal.alert('字段唯一标识只能选择一个！', 'warning');
            return false;
          } else {
            if (isNotEmpty(codesIndex)) {
              pkNames.push(state.selfCodes.data[codesIndex].code);
            }
            addCfgs.addsOtherConfig['pkNames'] = pkNames || [];
          }
          // 封装本功能列表数据
          state.selfCodes.data.forEach((item) => {
            addsConfigInfo[1].push(item.code);
          });
          addsConfigInfo[1] = addsConfigInfo[1].join('~');
          addsConfigInfo[2] = addsConfigInfo[2].join('~');
          addsConfigInfo = addsConfigInfo.join(',');
          addCfgs.addsConfigInfo = addsConfigInfo;
          Object.assign(addCfgs.addsOtherConfig, { ...state.formState });
          addCfgs.addsOtherConfig['codes'] = state.codes.data;
          addCfgs.addsOtherConfig['selfCodes'] = state.selfCodes.data;
          emit('changeModal', { type: 'ok', addCfgs });
        },
      };
      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style lang="less" scoped>
  .childfuncfield-adds-configinfo {
    .inputWrap {
      position: relative;
      .setIcon {
        position: absolute;
        top: 50%;
        right: 10px;
        transform: translate(0, -50%);
        cursor: pointer;
      }
    }
    .iconWrap {
      cursor: pointer;
    }
    .icon-class {
      font-size: 16px;
      width: 60px;
      height: 40px;
      background: #e6e6e6;
      text-align: center;
      line-height: 40px;
      border-radius: 2px;
      margin: 0 10px;
    }
    .tableWrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .table {
        width: 48%;
      }
    }
  }
</style>
<style lang="less">
  .childfuncfield-adds-configinfo {
    .childfuncfield-adds-configinfo-form {
      padding: 0;
    }
  }
</style>
